var prmoseHttp = require('../../utils/prmoseHttp.js');
var app = getApp();

Page({
  data: {
    enveOpened: false,
    imgHead:'https://rhi0.xiyun.net/zhuandian/image/',
    advList:[],
    isGo:true,
    isGoTb:false,
    isHideGo:false,
    dhAdvInfor:{},
    actOpenone:false,
    firstFinishedAwardAmount:0,
    redPacket:false,
    getPacket:false,
    kaiPacket:true,
    src:'XNTkxNjc4NzA1Ng==',
    userId:'',
    isGoTb:false,
    isHideGo:false,
    isTop:true,
  },
  onLoad() { 
    let that = this;
    that.innerAudioContext = my.createInnerAudioContext(); 
    //来源于优酷的音频码，用于直接播放。支持音频格式：AAC，MP3。如果开发者不传入音频码，控制台不会报错，但无音频播放。
    that.innerAudioContext.src = that.data.src; 
    //是否自动开始播放，默认为 false。
    that.innerAudioContext.autoplay = false;
    //是否循环播放，默认为 false。
    that.innerAudioContext.loop = false;
    //是否遵循系统静音开关，当此参数为 false 时，即使用户打开了静音开关，也能继续发出声音，默认值为 true (注意：此参数仅 iOS 支持)。
    that.innerAudioContext.obeyMuteSwitch = false;
    that.getDhInfo();
    if(my.getStorageSync({key:'userInfo'}).data.id){
      let id = my.getStorageSync({key:'userInfo'}).data.id;
      that.setData({
        userId:id,
      })
    }
  },
  onShow(){
    let that = this;
    that.getAdv();
    if(my.getStorageSync({key:'advInfor'}).data){
      if(my.getStorageSync({key:'advInfor'}).data.source === 2){
        that.checkStatus();
      }else if(my.getStorageSync({key:'advInfor'}).data.source === 4){
        that.checkRuohuo();
      }
    }
    if(that.data.isHideGo == true && that.data.isGoTb == true){
      that.endAdv(that.data.type);
    }
  },
  getCoinVoice(){
    this.innerAudioContext.stop()
    this.innerAudioContext.src = 'XNTkwODU5NTc3Mg==';
    this.innerAudioContext.play();
  },
  kaiRed(){
    this.innerAudioContext.stop()
    this.innerAudioContext.src = 'XNTkxNjc4NzA1Ng==';
    this.setData({
      kaiPacket:false,
      getPacket:true,
    })
    this.innerAudioContext.play();
    
  },
  closeRedPack(){
    this.setData({
      redPacket:false,
      kaiPacket:true,
      getPacket:false,
    })
  },
  //信息流广告
  getAdv(){
    let that = this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.task,{},1,'get').then(res=>{
      if(res.code == 200){
        that.setData({
          advList:res.data
        })
      }else{
        my.showToast({
          type:'fail',
          content:res.message
        })
      }
    }).catch(err=>{
      console.log(err);
    })
  },
  goAdv(e){
    let that = this;
    my.removeStorageSync({key: 'advInfor' });
    let url = e.currentTarget.dataset.url;
    let adId = e.currentTarget.dataset.adId;
    let clickLink = e.currentTarget.dataset.clickLink;
    let tagId = e.currentTarget.dataset.tagId;
    let currency = e.currentTarget.dataset.currency;
    let currencyType = e.currentTarget.dataset.currencyType;
    let source= e.currentTarget.dataset.source;
    let marketingtype = e.currentTarget.dataset.marketingtype;
    let type = e.currentTarget.dataset.type;
    let ext = e.currentTarget.dataset.ext;
    let viewDuration = e.currentTarget.dataset.viewDuration;
    my.setStorage({
      key:'advInfor',
      data:{
        adId:adId,
        clickLink:clickLink,
        tagId:tagId,
        currency:currency,
        currencyType:currencyType,
        marketingtype:marketingtype,
        source:source,
        viewDuration:viewDuration,
        ext:ext,
        type:type,
      }
    })
    that.goOutSide(source,type,url,ext,adId);
  },
  //云码广告，自营广告点击跳转
  goOutSide(source,type,url,ext,adId){
    let that = this;
    my.setStorage({key:"dhNum",data:3})
    if(source == 2){
      my.ap.navigateToAlipayPage({  
        path:encodeURIComponent(`https://render.alipay.com/p/h5/cloudcode-fe/redirect.html?target=${encodeURIComponent(url)}`)  
      })
    }else if(source == 4){
      that.setData({
        isGo:false,
      })
      if(type == 2 || type == 3){
        my.ap.navigateToAlipayPage({  
        path:ext.parameter,
        success: (res) => {
          // 跳转成功
          that.startWatch(adId);
        },
      })
      }else if(type == 4){
         my.ap.navigateToAlipayPage({  
          path:encodeURIComponent('https://render.alipay.com/p/s/i/?scheme='+encodeURIComponent('alipays://platformapi/startapp?appId=20000067&url='+ext.parameter)),
        })
        that.startWatch(adId);
      }else{
        my.navigateToMiniProgram({
        appId: ext.appid, // 16 位
        path: ext.address,
        success: (res) => {
          that.startWatch(adId);
        },
        fail: (res) => {
          my.alert({
            title: 'navigateToMiniProgram fail',
            content: JSON.stringify(res),
          });
        }
      });
      }
    }else if(source == 1){
      that.goBotttom();
    }else if(source == 5){
      that.collect();
    }
  },

  goBotttom(){
    let that = this;
    my.createSelectorQuery().select('#red-bao1').boundingClientRect().exec(res => {
      my.createSelectorQuery().select('#red-bao1').boundingClientRect().exec(ress =>{
        if(res[0].height){
          my.pageScrollTo({
            scrollTop:(res[0].height + ress[0].height),
          })
        }
      })
    })
  },
  //收藏
  collect(){
    my.ap.navigateToAlipayPage({
      appCode: 'myAppsGuide',         // 必填 固定值, 进入复访任务流程
      appParams: {
        operationKey: 'revisitGuide', // 必填 复访任务类型, 值可以是: revisitGuide(复访任务) 或 collectRevisitGuide(收藏复访任务)
        operationValue: '2021001114698471',   // 必填 商家的任务小程序app_id
        revisitSource: 'collectRevisitGuide',            // 必填 访问来源 自定义值, 会做透传
      },
      success:(res) => { 						  // 调用成功回调
        
      },
      fail: (res) => { 							  // 调用失败回调
        my.alert({ content: '失败：' + JSON.stringify(res) });
      }
    });
  },
  checkRuohuo(){
    let that = this;
    if(!that.data.isGo){
      let time = that.formDate();
      if(my.getStorageSync({key:'startTime'})){
        let startTime = my.getStorageSync({key:'startTime'}).data;
        let endTime = Date.parse(new Date())/1000;
        my.removeStorageSync({key:'startTime'})
        let overTime = endTime - startTime;
        let data = my.getStorageSync({key:"advInfor"}).data;
        if( overTime >= data.viewDuration){
          prmoseHttp.publicRequest(prmoseHttp.apiAddress.endBrowse,{
            advertId:data.adId,
            clientTime:time,
            druid:overTime,
          },1,'post').then(res=>{
            if(res.code == 200 && res.data.finished == true){
              if(res.data.ext != null){
                if(res.data.ext.firstFinished == true){
                  that.setData({
                    redPacket:true,
                    firstFinishedAwardAmount:res.data.ext.firstFinishedAwardAmount,
                    currency:res.data.currency,
                    currencyType:res.data.currencyType,
                  })
                }else{
                  my.alert({
                    title: '提示',
                    content: '未完成浏览或任务已下架',
                    buttonText: '确定',
                    success: () => {
                      my.removeStorageSync({key:'advInfor'})
                    }
                  })
                }
              }else{
                that.getCoinVoice();
                that.setData({
                  enveOpened:true,
                  currency:res.data.currency,
                  currencyType:res.data.currencyType,
                })
              }
            }
          })
        }else{
          that.getAdv();
          my.confirm({
            title: '温馨提示',
            content: '预览'+data.viewDuration+'秒以上才能获得奖励，本次预览时间'+overTime+'秒。\n温馨提示：直播间任务需要安装淘宝APP,否则无法完成，【直播任务多多，建议安装淘宝APP】',
            confirmButtonText: '继续完成任务',
            cancelButtonText: '我知道了',
            success: (result) => {
              if(result.confirm == true){
                that.goOutSide(data.source,data.type,data.url,data.ext,data.adId)
              }
            },
          });
        }
      }else{
        that.getAdv();
      }
    }else{
      that.getAdv();
    }
  },
  startWatch(adId){
    let that = this;
    let time = that.formDate();
      prmoseHttp.publicRequest(prmoseHttp.apiAddress.startBrowse,{
        advertId:adId,
        clientTime:time,
      },1,'post').then(res=>{
        console.log(res)
      })
  },
  formDate(){
    let date = new Date();
    var y = date.getFullYear();
	  var m = date.getMonth() + 1;
	  m = m < 10 ? ('0' + m) : m;
	  var d = date.getDate();
 	  d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
	  return y + '-' + m + '-' + d+' '+h+':'+minute +':'+second;
  },
  onEnveClose() {
    this.setData({
      'enveOpened': false, //导航栏高度 
    })
  },
  closeRed(){
    this.setData({
      enveOpened:true,
    })
  },
  getDhInfo(){
    let that = this;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.queryDh,{},1,'get').then(res=>{
      if(res.code == 200){
        that.setData({
          dhAdvInfor:res.data
        })
      }
    }).catch(err=>{})
  },
  goInfor(e){
    this.setData({
      isGoTb:true,
      type:2,
    })
    let startTime = Date.parse(new Date())/1000;
    my.setStorage({key:"dhBrowseTime",data:startTime})
  },
  transTime(time){
    let date = new Date(time);
    var y = date.getFullYear();
	  var m = date.getMonth() + 1;
	  m = m < 10 ? ('0' + m) : m;
	  var d = date.getDate();
 	  d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    h = h < 10 ? ('0' + h) : h;
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
	  return y + '-' + m + '-' + d+' '+h+':'+minute +':'+second;
  },
  //开始浏览灯火广告
  startAdv(type){
    let that = this;
    let startime = my.getStorageSync({key:'dhBrowseTime'}).data;
    let time = that.transTime(startime*1000);
    let nowTime = Date.parse(new Date())/1000;
    if(nowTime - startime > 1){
      that.setData({
        isGoTb:false,
        isHideGo:false,
      })
    }else{
      prmoseHttp.publicRequest(prmoseHttp.apiAddress.startDh,{
        clientTime:time,
        type:type,
      },1,'post').then(res=>{
        console.log(res)
      })
    }
  },
  //结束浏览灯火广告
  endAdv(type){
    let that = this;
    if(that.data.isHideGo){
      let time = that.formDate();
      if(my.getStorageSync({key:'dhBrowseTime'}).data){
        let startTime = my.getStorageSync({key:'dhBrowseTime'}).data;
        let endTime = Date.parse(new Date())/1000;
        my.removeStorageSync({key:'dhBrowseTime'})
        let overTime = endTime - startTime;
        if( overTime >= that.data.dhAdvInfor.viewDuration){
          prmoseHttp.publicRequest(prmoseHttp.apiAddress.endDh,{
            clientTime:time,
            druid:overTime,
            type:type,
          },1,'post').then(res=>{
            if(res.code == 200 && res.data.finished == true){
              if(res.data.ext != null){
                if(res.data.ext.firstFinished == true){
                  // if(that.data.dhAwardDialog == true){
                    that.setData({
                      redPacket:true,
                      firstFinishedAwardAmount:res.data.ext.firstFinishedAwardAmount,
                      currency:res.data.currency,
                      currencyType:res.data.currencyType,
                    })
                  // }
                  that.getDhInfo();
                  my.removeStorageSync({key:'dhBrowseTime'})
                }else{
                  // if(that.data.dhAwardDialog == true){
                    let viewDuration = that.data.dhAdvInfor.viewDuration;
                    my.alert({
                      title: '提示',
                      content: '商品浏览时长不够'+viewDuration+'秒,没有红包哦～',
                      buttonText: '确定',
                      success: () => {
                        
                      }
                    })
                  // }
                }
                my.removeStorageSync({key:'dhBrowseTime'})
              }else{
                // if(that.data.dhAwardDialog == true){
                  that.getCoinVoice();
                  that.setData({
                    enveOpened:true,
                    currency:res.data.currency,
                    currencyType:res.data.currencyType,
                  })
                // }
                that.getDhInfo();
                my.removeStorageSync({key:'dhBrowseTime'})
              }
            }else{
              // if(that.data.dhAwardDialog == true){
                my.alert({
                  title: '提示',
                  content: res.message,
                  buttonText: '确定',
                  success: () => {
                    
                  }
                })
              // }
            }
          })
        }else{
          let viewDuration = that.data.dhAdvInfor.viewDuration;
          // if(that.data.dhAwardDialog == true){
            my.alert({
              title: '温馨提示',
              content: '商品浏览时长不够'+viewDuration+'秒,没有红包哦～',
              buttonText: '确定',
              success: () => {
                
              }
            })
          // }
        }
      }
    }
  },
  checkStatus(){
    let that = this;
    let adv = my.getStorageSync({key:'advInfor'}).data;
    prmoseHttp.publicRequest(prmoseHttp.apiAddress.checkAdv,{
      adId:adv.adId,
      clickLink:adv.clickLink,
      tagId:adv.tagId,
      marketingType:adv.marketingtype,
    },1,'get').then(res=>{
      if(res.code == 200 && res.data.finished == true){
        if(res.data.ext != null){
          if(res.data.ext.firstFinished == true){
            that.setData({
              redPacket:true,
              firstFinishedAwardAmount:res.data.ext.firstFinishedAwardAmount,
              currency:res.data.currency,
              currencyType:res.data.currencyType,
            })
          }else{
            my.alert({
              title: '提示',
              content: '未完成浏览或任务已下架',
              buttonText: '确定',
              success: () => {
                my.removeStorageSync({key:'advInfor'})
              }
            })
          }
        }else{
          that.getCoinVoice();
          that.setData({
            enveOpened:true,
            currency:res.data.currency,
            currencyType:res.data.currencyType,
          })
        }
        my.removeStorageSync({key:'advInfor'})
      }else{
        my.alert({
          title: '提示',
          content: '未完成浏览或任务已下架',
          buttonText: '确定',
          success: () => {
            my.removeStorageSync({key:'advInfor'})
          }
        })
      }
    })
  },
  //获取灯火引导页开关状态
  getYDYStatus(sta1,sta2){
    this.setData({
      dhAdvertGuide:sta1,
      dhAwardDialog:sta2,
    })
  },
  //点击灯火广告
  goInfor(){
    this.setData({
      isGoTb:true,
      type:2,
    })
    let startTime = Date.parse(new Date())/1000;
    my.setStorage({key:"dhBrowseTime",data:startTime})
    my.setStorage({key:"dhNum",data:1})
  },
  //获取灯火信息流广告信息
  getDhInfo(e){
    if(e){
      this.setData({
        dhAdvInfor:e
      })
    }
  },
  //获取灯火广告banner广告信息
  getBannerInfo(e){
    if(e){
      this.setData({
        bannerInfor:e
      })
    }
  },
  onHide() {
    let that = this;
    that.setData({
      isHideGo:true,
    })
    if(that.data.isGoTb == true){
      that.startAdv(that.data.type);
    }
  },
  onShareAppMessage () {
    return {
      title: '挣点', // 标题
      desc: '任务多多，天天领取现金红包', // 描述
      path: 'pages/index/index?userid='+this.data.userId, // 分享的小程序页面
      success(res){
        my.navigateTo({
          url: '/pages/shareSuccess/shareSuccess'
        }); 
      },
      fail(res){
        console.log('fail',res)
      },
    }
  },
});
